﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using TransCode.Entitys;
using System.ComponentModel;

namespace TransCode.Logic
{
    public class TargetObjectLogic
    {
        MongoDatabase db = MongoDbHelper.DbInstance();

        public event EventHandler<TargetObjectFindResultArgs> TargetObjectFindHandler;

        public void Finded(TargetObject obj)
        {
            if (TargetObjectFindHandler != null)
                TargetObjectFindHandler(this, new TargetObjectFindResultArgs() { Result = obj });
        }

        public void Querys(IDictionary<string, object> args)
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler((object sender, DoWorkEventArgs e) =>
            {
                var query = Query.And(
                    Query.GT("EndTime", (DateTime)args["BeginTime"]),
                    Query.LT("BeginTime", (DateTime)args["EndTime"]));

                var videos = db.GetCollection<Video>("Video").Find(query).ToList();

                foreach (var video in videos)
                {
                    foreach (var target in video.TargetList)
                    {
                        foreach (var tobj in target.ObjectList)
                        {
                            if (tobj.Type.ToLower() == args["Type"].ToString().ToLower())
                            {
                                Finded(tobj);
                                continue;
                            }
                            if (tobj.ImageParameterList.Count(it => it.Color.ToLower() == args["Color"].ToString().ToLower()) > 0)
                            {
                                Finded(tobj);
                                continue;
                            }
                        }
                    }
                }
            });
            worker.RunWorkerAsync();

        }


    }

    public class TargetObjectFindResultArgs : EventArgs
    {
        public TargetObject Result { get; set; }
    }
}
